<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="回收编码" prop="recycleCode">
        <el-input
          v-model="queryParams.recycleCode"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类目" prop="category">
        <el-select
          v-model="queryParams.category"
          filterable
          clearable
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择商品类目"
          style="width: 150px"
        >
          <el-option
            v-for="item in goods_category"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品品牌" prop="brand">
        <el-select
          v-model="queryParams.brand"
          filterable
          reserve-keyword
          clearable
          style="width: 230px"
          allow-create
          default-first-option
          placeholder="请选择品牌"
        >
          <el-option
            v-for="item in item_brand"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编码" prop="ref">
        <el-input
          v-model="queryParams.ref"
          style="width: 205px"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品状态" prop="itemStatus">
        <el-select
          v-model="queryParams.itemStatus"
          placeholder="状态"
          style="width: 90px"
          clearable
        >
          <el-option
            v-for="i in item_status"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="回收价格" prop="recyclePrice">
        <el-input
          v-model="queryParams.recyclePrice"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回收人" prop="recyclePersonId">
        <el-select
          v-model="queryParams.recyclePersonId"
          filterable
          remote
          reserve-keyword
          placeholder="请选择"
          :remote-method="getUserOption"
          :loading="userLoading"
          style="width: 220px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间">
        <el-date-picker
          v-model="warehouseEntryTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          style="width: 230px"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="打款状态" prop="mPaymentStatus">
        <el-select
          v-model="queryParams.mPaymentStatus"
          placeholder="状态"
          style="width: 90px"
          clearable
        >
          <el-option
            v-for="i in payment_status"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打款时间">
        <el-date-picker
          v-model="mPaymentTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 230px"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="下架时间">
        <el-date-picker
          v-model="salesTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          style="width: 230px"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="销售方" prop="salesPersonId">
        <el-select
          v-model="queryParams.salesPersonId"
          filterable
          remote
          reserve-keyword
          style="width: 220px"
          placeholder="请选择销售方"
          :remote-method="getUserOption"
          clearable
          :loading="userLoading"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="到款状态" prop="cPaymentStatus">
        <el-select
          v-model="queryParams.cPaymentStatus"
          placeholder="状态"
          style="width: 80px"
          clearable
        >
          <el-option
            v-for="i in payment_status"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="到款时间">
        <el-date-picker
          v-model="cPaymentTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          style="width: 230px"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="维修人" prop="maintenancePersonId">
        <el-select
          v-model="queryParams.maintenancePersonId"
          filterable
          clearable
          remote
          reserve-keyword
          placeholder="请选择"
          :remote-method="getUserOption"
          :loading="userLoading"
          style="width: 220px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNo">
        <el-input
          v-model="queryParams.expressNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          v-hasPermi="['erp:stockManager:query']"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['erp:stockManager:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erp:stockManager:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      height="55vh"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="商品正面图"
        prop="watchImageUrl"
        align="center"
        width="110"
      >
        <template #default="scope">
          <div style="display: flex; align-items: center; width: 50px">
            <el-image
              :src="scope.row.watchImageUrl"
              :preview-src-list="[scope.row.watchImageUrl]"
              preview-teleported
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品背面图"
        prop="watchImageUrlBack"
        align="center"
        width="110"
      >
        <template #default="scope">
          <div style="display: flex; align-items: center; width: 50px">
            <el-image
              :src="scope.row.watchImageUrlBack"
              :preview-src-list="[scope.row.watchImageUrlBack]"
              preview-teleported
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="回收编号" prop="recycleCode" align="center" />
      <el-table-column label="品牌" prop="brand" align="center">
        <template #default="scope">
          <dict-tag
            v-if="scope.row.brand"
            :options="item_brand"
            :value="scope.row.brand"
          />
          <span v-else>{{ scope.row.brandName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号" prop="model" align="center" />
      <el-table-column label="编码" prop="ref" align="center" />
      <el-table-column
        label="打款时间"
        prop="mPaymentTime"
        align="center"
        width="100"
      />
      <el-table-column label="回收人" prop="recyclePerson" align="center" />
      <el-table-column label="回收价格" prop="recyclePrice" align="center" />
      <el-table-column label="成交价" prop="salesPrice" align="center" />
      <el-table-column
        label="下架时间"
        prop="salesTime"
        align="center"
        width="100"
      />
      <el-table-column label="销售方" prop="salesPerson" align="center" />
      <el-table-column
        label="销售提成"
        prop="salesCommissions"
        align="center"
      />
      <el-table-column label="运费" prop="expressFee" align="center" />
      <el-table-column label="维修成本" prop="maintenanceCost" align="center" />
      <el-table-column
        label="维修提成"
        prop="maintenanceCommissions"
        align="center"
      />
      <el-table-column
        label="维修人员"
        prop="maintenancePerson"
        align="center"
      />
      <el-table-column
        label="维修时间"
        prop="maintenanceTime"
        align="center"
        width="100"
      />
      <el-table-column
        label="抛光费"
        prop="polishFee"
        align="center"
        width="100"
      />
      <el-table-column
        label="服务费"
        prop="serviceFee"
        align="center"
        width="100"
      />
      <el-table-column
        label="售后费"
        prop="afterSalesFee"
        align="center"
        width="100"
      />
      <el-table-column label="商品状态" prop="itemStatus" align="center">
        <template #default="scope">
          <dict-tag :options="item_status" :value="scope.row.itemStatus" />
        </template>
      </el-table-column>
      <el-table-column label="故障描述" prop="maintenanceDesc" align="center" />
      <el-table-column label="利润" prop="profit" align="center" />
      <el-table-column label="打款状态" prop="mpaymentStatus" align="center">
        <template #default="scope">
          <dict-tag
            :options="payment_status"
            :value="scope.row.mpaymentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="回收备注" prop="recycleRemark" align="center" />
      <el-table-column label="销售备注" prop="salesRemark" align="center" />
      <el-table-column label="其它" prop="otherRemark" align="center" />
      <el-table-column
        label="入库时间"
        prop="warehouseEntryTime"
        align="center"
        width="100"
      />
      <el-table-column label="售出客户" prop="mcustomerName" align="center" />
      <el-table-column label="到款状态" prop="cpaymentStatus" align="center">
        <template #default="scope">
          <dict-tag
            :options="payment_status"
            :value="scope.row.cpaymentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="到款方式" prop="paymentWay" align="center" />
      <el-table-column
        label="到款时间"
        prop="cPaymentTime"
        align="center"
        width="100"
      />
      <el-table-column label="售出客户" prop="ccustomerName" align="center" />
      <el-table-column
        label="打款时间"
        prop="mPaymentTime"
        align="center"
        width="100"
      />
      <el-table-column label="回收人员" prop="recyclePerson" align="center" />
    </el-table>
    <div class="footer-msg">
      <p>
        <i class="el-icon-warning blue-text"></i>
        数量总和:
        <span class="blue-text">{{ summaryInfo.sumCount || "N/A" }}</span>
      </p>
      <p>
        <i class="el-icon-warning blue-text"></i>
        总利润:
        <span class="blue-text">{{ summaryInfo.sumProfit || "N/A" }}</span>
      </p>
      <p>
        服务费:<span class="blue-text">{{
          summaryInfo.sumServiceFee || "N/A"
        }}</span>
      </p>
      <p>
        抛光费:<span class="blue-text">{{
          summaryInfo.sumPolishFee || "N/A"
        }}</span>
      </p>
      <p>
        售后费:<span class="blue-text">{{
          summaryInfo.sumAfterSalesFee || "N/A"
        }}</span>
      </p>
      <p>
        邮费金额总和:<span class="blue-text">{{
          summaryInfo.sumExpressFeeAmount || "N/A"
        }}</span>
      </p>
      <p>
        销售提成总和:<span class="blue-text">{{
          summaryInfo.sumSalesCommissions || "N/A"
        }}</span>
      </p>
      <p>
        销售成交总金额:<span class="blue-text">{{
          summaryInfo.sumSalesAmount || "N/A"
        }}</span>
      </p>
      <p>
        回收成本总金额:<span class="blue-text">{{
          summaryInfo.sumRecycleAmount || "N/A"
        }}</span>
      </p>
      <p>
        维修成本总金额:<span class="blue-text">{{
          summaryInfo.sumMaintenanceCost || "N/A"
        }}</span>
      </p>
      <p>
        维修提成总金额:<span class="blue-text">{{
          summaryInfo.sumMaintenanceComissions || "N/A"
        }}</span>
      </p>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="StockManager">
import { listTable, dowloadErrorExcel } from "@/api/stock/stockManager";
import { optionSelect } from "@/api/system/skesItem";
import { getToken } from "@/utils/auth";
import { userOptionSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const summaryInfo = ref({});
const selectionData = ref([]);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);

const stockOutTime = ref([]);
const mPaymentTime = ref([]);
const cPaymentTime = ref([]);
const recycleTime = ref([]);
const warehouseEntryTime = ref([]);
const salesTime = ref([]);
const maintenanceTime = ref([]);
const { item_status } = proxy.useDict("item_status");
const { payment_status } = proxy.useDict("payment_status");
const { item_brand } = proxy.useDict("item_brand");
const { goods_category } = proxy.useDict("goods_category");
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemId: undefined,
    maintenancePersonId: undefined,
    recyclePersonId: undefined,
    itemStatus: undefined,
    remark: undefined,
    recycleCode: undefined,
    recyclePrice: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: i.id,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
        recyclePrice: i.recyclePrice,
      };
    });
    remoteLoading.value = false;
  }
}
getItemOption(" ");
/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: userId,
        label: `${userId},${nickName},${userName}`,
      };
    });
    userLoading.value = false;
  }
}
getUserOption(" ");

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/stock/stockManager/importData",
});
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/stock/stockManager/importTemplate", {}, `商品库存信息.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = async (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  if (response.code === 500) {
    proxy.download(
      "stock/stockManager/dowloadErrorExcel/" + response.data,
      {},
      `导入失败数据.xlsx`
    );
  }
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 查询列表 */
function getList() {
  loading.value = true;
  const [beginStockOutTime, endStockOutTime] = stockOutTime.value;
  const [beginMPaymentTime, endMPaymentTime] = mPaymentTime.value;
  const [beginCPaymentTime, endCPaymentTime] = cPaymentTime.value;
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  const [beginWarehouseEntryTime, endWarehouseEntryTime] =
    warehouseEntryTime.value;
  const [beginSalesTime, endSalesTime] = salesTime.value;
  const [beginMaintenanceTime, endMaintenanceTime] = maintenanceTime.value;
  const params = {
    beginStockOutTime,
    endStockOutTime,
    beginMPaymentTime,
    endMPaymentTime,
    beginCPaymentTime,
    endCPaymentTime,
    beginRecycleTime,
    endRecycleTime,
    beginWarehouseEntryTime,
    endWarehouseEntryTime,
    beginSalesTime,
    endSalesTime,
    beginMaintenanceTime,
    endMaintenanceTime,
  };
  listTable({ ...queryParams.value, params }).then((response) => {
    dataList.value = response.rows;
    summaryInfo.value = { ...response, rows: undefined };
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  stockOutTime.value = [];
  mPaymentTime.value = [];
  cPaymentTime.value = [];
  recycleTime.value = [];
  warehouseEntryTime.value = [];
  salesTime.value = [];
  maintenanceTime.value = [];
  handleQuery();
  handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
  const [beginStockOutTime, endStockOutTime] = stockOutTime.value;
  const [beginMPaymentTime, endMPaymentTime] = mPaymentTime.value;
  const [beginCPaymentTime, endCPaymentTime] = cPaymentTime.value;
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  const [beginWarehouseEntryTime, endWarehouseEntryTime] =
    warehouseEntryTime.value;
  const [beginSalesTime, endSalesTime] = salesTime.value;
  const [beginMaintenanceTime, endMaintenanceTime] = maintenanceTime.value;
  const params = {
    beginStockOutTime,
    endStockOutTime,
    beginMPaymentTime,
    endMPaymentTime,
    beginCPaymentTime,
    endCPaymentTime,
    beginRecycleTime,
    endRecycleTime,
    beginWarehouseEntryTime,
    endWarehouseEntryTime,
    beginSalesTime,
    endSalesTime,
    beginMaintenanceTime,
    endMaintenanceTime,
  };
  proxy.download(
    "stock/stockManager/export",
    {
      ...queryParams.value,
      params,
    },
    `stockManager_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {}
getList();
</script>
